﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CERT.Services.DAL;
using System.Configuration;
using RefactorThis.GraphDiff;

namespace CERT.Services
{
    public partial class NETServices : CERT.Services.INETServices
    {

        public Location GetLocation(System.Linq.Expressions.Expression<Func<Location, bool>> predicate)
        {
            Location entry = null;
                      
            using (var context = new NETEntities())
            {
                try
                {
                    entry = context.Set<Location>().Include("LocationHazards").FirstOrDefault<Location>(predicate);
                }
                catch (Exception ex)
                { }

                return entry;
            }
        }

        public void DeleteLocation(int id)
        {

            //todo ideally, you check and see if this the user's only association.
            //if so, delete them.
            using (var context = new NETEntities())
            {
                var entity = context.Set<Location>().FirstOrDefault(a => a.Id == id);
                context.Set<Location>().Remove(entity);
                context.SaveChanges();
            }

        }

        public void UpdateLocation(Location location, int locationId)
        {
            //replace with...
            //http://refactorthis.wordpress.com/2012/12/11/introducing-graphdiff-for-entity-framework-code-first-allowing-automated-updates-of-a-graph-of-detached-entities/#comments

            using (var context = new NETEntities())
            {
                context.UpdateGraph<Location>(location, map => map
               .OwnedCollection(p => p.LocationHazards) 
              
   );


                var existing = context.Locations.Find(locationId);
                context.Entry(existing).CurrentValues.SetValues(location);


                context.SaveChanges();
            }

        }

        public void AddLocation(Location entity)
        {
            using (var context = new NETEntities())
            {
                if (entity.Incident == null)
                {
                    var incident = context.Incidents.FirstOrDefault(a => a.Id == entity.IncidentId);
                    entity.Incident = incident;
                }

                    //var AddLocation = entity.Locations.FirstOrDefault(a => a.Id == 0);
                    context.Set<Location>().Add(entity);
                  context.SaveChanges();

            }
        }

    }
}